package com.itheima.reggie.controller;

import com.alibaba.druid.sql.visitor.functions.Lcase;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.BackingStoreException;

@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartCotroller {

    @Autowired
    private ShoppingCartService shoppingCartService;

    //查询购物车列表--查询当前用户购物车表
    @GetMapping("/list")
    public R list() {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        lqw.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        return R.success(list);
    }

    //添加购物车
    @PostMapping("/add")
    public R save(@RequestBody ShoppingCart shoppingCart) {
        //查看当前登录用户
        Long currentId = BaseContext.getCurrentId();
        //查看用户哟没有添加过菜品或者套餐
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();

        lqw.eq(ShoppingCart::getUserId, currentId);
        lqw.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        lqw.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        ShoppingCart shoppingCartDB  = shoppingCartService.getOne(lqw);//是菜品或者是套餐

        // 如果有 数量+1
        if (shoppingCartDB!=null){
            shoppingCartDB.setNumber( shoppingCartDB.getNumber()+1);
            shoppingCartService.updateById(shoppingCartDB);
            return R.success(shoppingCartDB);
        }else{
            //3. 如果没有 直接添加
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            //返回购物车信息
            return R.success(shoppingCart);
        }
    }
    @DeleteMapping("/clean")
    public R delete(){
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        shoppingCartService.remove(lqw);
        return R.success("清楚成功");
    }
}
